﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using NPOI.HSSF.UserModel;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
using System.Drawing;

namespace EquipmentConfig.Class
{
    public class ExcelManage
    {
        public class ExcelTitleExplain
        {
            public string TitleName { get; set; }
            public string ColumnName { get; set; }
        }
        public static string PublicExcepTemplatePath = AppDomain.CurrentDomain.BaseDirectory + "\\Template\\Template.xls";
        //public byte[] GetExcel(DataTable table, List<ExcelTitleExplain> listTitleInfo)
        //{
        //    //创建工作簿对象
        //    HSSFWorkbook hssfworkbook;
        //    //打开模板文件到文件流中
        //    using (FileStream file = new FileStream(PublicExcepTemplatePath, FileMode.Open, FileAccess.Read))
        //    {
        //        //将文件流中模板加载到工作簿对象中
        //        hssfworkbook = new HSSFWorkbook(file);
        //    }
        //    ISheet sheet = hssfworkbook.GetSheet("Sheet1");
        //    ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
        //    IDataFormat format = hssfworkbook.CreateDataFormat();
        //    cellStyle.DataFormat = format.GetFormat("$#,##0.00");
        //    cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
        //    cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
        //    cellStyle.Alignment = HorizontalAlignment.RIGHT;

        //    ICellStyle cellStyle1 = hssfworkbook.CreateCellStyle();
        //    cellStyle1.Alignment = HorizontalAlignment.CENTER;

        //    #region 初始化表頭
        //    var titleRow = sheet.GetRow(0);
        //    if (titleRow == null)
        //    {
        //        titleRow = sheet.CreateRow(0);
        //    }
        //    if (listTitleInfo == null)
        //    {
        //        listTitleInfo = new List<ExcelTitleExplain>();
        //        foreach (DataColumn col in table.Columns)
        //        {
        //            listTitleInfo.Add(new ExcelTitleExplain { ColumnName = col.ColumnName, TitleName = col.ColumnName });
        //        }
        //    }
        //    for (int i = 0; i < listTitleInfo.Count; i++)
        //    {
        //        var cell = titleRow.GetCell(i);
        //        if (cell == null)
        //        {
        //            cell = titleRow.CreateCell(i);
        //        }
        //        cell.SetCellValue(listTitleInfo[i].TitleName);
        //        cell.CellStyle = cellStyle1;
        //    }
        //    #endregion

        //    #region 填充表數據
        //    for (int i = 0; i < table.Rows.Count; i++)
        //    {
        //        int ExcelRowIndex = i + 1;
        //        var eRow = sheet.GetRow(ExcelRowIndex);
        //        if (eRow == null)
        //        {
        //            eRow = sheet.CreateRow(ExcelRowIndex);
        //        }
        //        for (int j = 0; j < listTitleInfo.Count; j++)
        //        {
        //            var cell = eRow.GetCell(j);
        //            if (cell == null)
        //            {
        //                cell = eRow.CreateCell(j);
        //            }
        //            var DataCell = table.Rows[i][listTitleInfo[j].ColumnName];
        //            cell.SetCellValue(DataCell == DBNull.Value ? null : DataCell.ToString());
        //        }
        //    }
        //    #endregion
        //    byte[] buffer = null;
        //    using (MemoryStream ms = new MemoryStream())
        //    {
        //        hssfworkbook.Write(ms);
        //        buffer = ms.GetBuffer();
        //    }
        //    return buffer;
        //}

        #region Excel2003
        /// <summary>
        /// 将Excel文件中的数据读出到DataTable中(xls)
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static DataTable ExcelToTableForXLS(string file)
        {
            DataTable dt = new DataTable();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                HSSFWorkbook hssfworkbook = new HSSFWorkbook(fs);
                ISheet sheet = hssfworkbook.GetSheetAt(0);

                //表头
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueTypeForXLS(header.GetCell(i) as HSSFCell);
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                        //continue;
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //数据
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueTypeForXLS(sheet.GetRow(i).GetCell(j) as HSSFCell);
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// 将DataTable数据导出到Excel文件中(xls)
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="file"></param>
        public static void TableToExcelForXLS(DataTable dt, string file)
        {
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            ISheet sheet = hssfworkbook.CreateSheet("Sheet1");

            //表头
            //IRow row = sheet.CreateRow(0);
            //for (int i = 0; i < dt.Columns.Count; i++)
            //{
            //    ICell cell = row.CreateCell(i);
            //    cell.SetCellValue(dt.Columns[i].ColumnName);
            //}

            //数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell cell = row1.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }

            //转为字节数组
            MemoryStream stream = new MemoryStream();
            hssfworkbook.Write(stream);
            var buf = stream.ToArray();

            //保存为Excel文件
            using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
        }

        /// <summary>
        /// 获取单元格类型(xls)
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValueTypeForXLS(HSSFCell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:
                    return null;
                case CellType.Boolean: //BOOLEAN:
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:
                    return cell.NumericCellValue;
                case CellType.String: //STRING:
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:
                default:
                    return "=" + cell.CellFormula;
            }
        }
        #endregion


        #region Excel2007
        /// <summary>
        /// 将Excel文件中的数据读出到DataTable中(xlsx)
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static DataTable ExcelToTableForXLSX(string file)
        {
            DataTable dt = new DataTable();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                XSSFWorkbook xssfworkbook = new XSSFWorkbook(fs);
                ISheet sheet = xssfworkbook.GetSheetAt(0);

                //表头
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueTypeForXLSX(header.GetCell(i) as XSSFCell);
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                        //continue;
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //数据
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueTypeForXLSX(sheet.GetRow(i).GetCell(j) as XSSFCell);
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// 将DataTable数据导出到Excel文件中(xlsx)
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="file"></param>
        public static void TableToExcelForXLSX(DataTable dt, string file, string strSheetName)
        {
            XSSFWorkbook xssfworkbook = new XSSFWorkbook();
            ISheet sheet = xssfworkbook.CreateSheet(strSheetName);
            ICellStyle cellStyle1 = xssfworkbook.CreateCellStyle();
            cellStyle1.Alignment = HorizontalAlignment.Center;

            //表头
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
                cell.CellStyle = cellStyle1;
                sheet.SetColumnWidth(i, 100 * 50);
                if (strSheetName == "历史记录" && dt.Columns[i].ColumnName == "编号")
                {
                    sheet.SetColumnWidth(i, 50 * 50);
                }
            }

            //数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell cell = row1.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }

            //转为字节数组
            MemoryStream stream = new MemoryStream();
            xssfworkbook.Write(stream);
            var buf = stream.ToArray();

            //保存为Excel文件
            using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
        }

        /// <summary>
        /// 将历史数据数据导出到Excel文件中(xlsx)
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="file"></param>
        public static void HisDataToExcelForXLSX(DataTable dt, string file, string strTitle)
        {
            XSSFWorkbook xssfworkbook = new XSSFWorkbook();
            ISheet sheet = xssfworkbook.CreateSheet();

            CellRangeAddress region = new CellRangeAddress(0, 0, 0, dt.Columns.Count - 1);
            sheet.AddMergedRegion(region);
            IRow rowTitle = sheet.CreateRow(0);
            ICell cellTitle = rowTitle.CreateCell(0);
            cellTitle.SetCellValue(strTitle);
            ICellStyle cellStyle2 = xssfworkbook.CreateCellStyle();
            cellStyle2.Alignment = HorizontalAlignment.Left;

            IFont font = xssfworkbook.CreateFont(); //创建字体
            font.IsBold = true; //字体加粗
            cellStyle2.SetFont(font);
            cellTitle.CellStyle = cellStyle2;
            sheet.SetColumnWidth(0, 100 * 50);

            //表头
            IRow row = sheet.CreateRow(1);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
                ICellStyle cellStyle1 = xssfworkbook.CreateCellStyle();
                cellStyle1.Alignment = HorizontalAlignment.Center;
                cell.CellStyle = cellStyle1;
                if (i == 0)
                {
                    sheet.SetColumnWidth(i, 100 * 70);
                }
                else
                {
                    sheet.SetColumnWidth(i, 100 * 50);
                }
            }

            //数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 2);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell cell = row1.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }

            //转为字节数组
            MemoryStream stream = new MemoryStream();
            xssfworkbook.Write(stream);
            var buf = stream.ToArray();

            //保存为Excel文件
            using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
        }

        /// <summary>
        /// 将DataTable数据导出到Excel文件中(xlsx)
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="file"></param>
        public static void TableToExcelForXLSXs(List<DataTable> dtList, string file, List<string> strSheetNames)
        {
            XSSFWorkbook xssfworkbook = new XSSFWorkbook();

            for (int m = 0; m < dtList.Count; m++)
            {
                ISheet sheet = xssfworkbook.CreateSheet(strSheetNames[m]);
                ICellStyle cellStyle1 = xssfworkbook.CreateCellStyle();
                cellStyle1.Alignment = HorizontalAlignment.Center;

                //表头
                IRow row = sheet.CreateRow(0);
                for (int i = 0; i < dtList[m].Columns.Count; i++)
                {
                    ICell cell = row.CreateCell(i);
                    cell.SetCellValue(dtList[m].Columns[i].ColumnName);
                    cell.CellStyle = cellStyle1;
                    sheet.SetColumnWidth(i, 100 * 50);
                    //if (strSheetName == "历史记录" && dt.Columns[i].ColumnName == "编号")
                    //{
                    //    sheet.SetColumnWidth(i, 50 * 50);
                    //}
                }

                //数据
                for (int i = 0; i < dtList[m].Rows.Count; i++)
                {
                    IRow row1 = sheet.CreateRow(i + 1);
                    for (int j = 0; j < dtList[m].Columns.Count; j++)
                    {
                        ICell cell = row1.CreateCell(j);
                        cell.SetCellValue(dtList[m].Rows[i][j].ToString());
                    }
                }
            }

            //转为字节数组
            MemoryStream stream = new MemoryStream();
            xssfworkbook.Write(stream);
            var buf = stream.ToArray();

            //保存为Excel文件
            using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
        }

        /// <summary>  
        /// 将excel导入到datatable  
        /// </summary>  
        /// <param name="filePath">excel路径</param>  
        /// <param name="isColumnName">第一行是否是列名</param>  
        /// <returns>返回datatable</returns>  
        public static DataTable ExcelToDataTable(string filePath, bool isColumnName)
        {
            DataTable dataTable = null;
            DataColumn column = null;
            DataRow dataRow = null;
            IWorkbook workbook = null;
            ISheet sheet = null;
            IRow row = null;
            ICell cell = null;
            int startRow = 0;
            try
            {

                    string extension = System.IO.Path.GetExtension(filePath);
                    FileStream fs = File.OpenRead(filePath);
                    if (extension.Equals(".xls"))
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                    else
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    fs.Close();

                if (workbook != null)
                {
                    sheet = workbook.GetSheetAt(0);//读取第一个sheet，当然也可以循环读取每个sheet  
                    dataTable = new DataTable();
                    if (sheet != null)
                    {
                        int rowCount = sheet.LastRowNum;//总行数  
                        if (rowCount > 0)
                        {
                            IRow firstRow = sheet.GetRow(0);//第一行  
                            int cellCount = firstRow.LastCellNum;//列数  

                            //构建datatable的列  
                            if (isColumnName)
                            {
                                startRow = 1;//如果第一行是列名，则从第二行开始读取  
                                for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                {
                                    cell = firstRow.GetCell(i);
                                    if (cell != null)
                                    {
                                        if (cell.StringCellValue != null)
                                        {
                                            column = new DataColumn(cell.StringCellValue);
                                            dataTable.Columns.Add(column);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                {
                                    column = new DataColumn("column" + (i + 1));
                                    dataTable.Columns.Add(column);
                                }
                            }

                            //填充行  
                            for (int i = startRow; i <= rowCount; ++i)
                            {
                                row = sheet.GetRow(i);
                                if (row == null) continue;

                                dataRow = dataTable.NewRow();
                                for (int j = row.FirstCellNum; j < cellCount; ++j)
                                {
                                    cell = row.GetCell(j);
                                    if (cell == null)
                                    {
                                        dataRow[j] = "";
                                    }
                                    else
                                    {
                                        //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)  
                                        switch (cell.CellType)
                                        {
                                            case CellType.Blank:
                                                dataRow[j] = "";
                                                break;
                                            case CellType.Numeric:
                                                short format = cell.CellStyle.DataFormat;
                                                //对时间格式（2015.12.5、2015/12/5、2015-12-5等）的处理  
                                                if (format == 14 || format == 31 || format == 57 || format == 58)
                                                    dataRow[j] = cell.DateCellValue;
                                                else
                                                    dataRow[j] = cell.NumericCellValue;
                                                break;
                                            case CellType.String:
                                                dataRow[j] = cell.StringCellValue;
                                                break;
                                        }
                                    }
                                }
                                dataTable.Rows.Add(dataRow);
                            }
                        }
                    }
                }
                return dataTable;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取单元格类型(xlsx)
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValueTypeForXLSX(XSSFCell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:
                    return null;
                case CellType.Boolean: //BOOLEAN:
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:
                    return cell.NumericCellValue;
                case CellType.String: //STRING:
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:
                default:
                    return "=" + cell.CellFormula;
            }
        }
        #endregion
    }
}
